package com.lyz.myself.controller;

import com.github.pagehelper.PageInfo;
import com.lyz.myself.config.utils.JwtUtil;
import com.lyz.myself.config.utils.Result;
import com.lyz.myself.config.utils.base.CodeMsg;
import com.lyz.myself.config.utils.oss.AliyunOSSUtil;
import com.lyz.myself.config.utils.util.DateUtil;
import com.lyz.myself.pojo.Po.*;
import com.lyz.myself.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @program: myself
 * @Date: 2019/2/14 16:03
 * @Author: Mr.Deng
 * @Description:
 */
@Api(description = "线索")
@RestController
@RequestMapping("/leads")
public class LeadsController extends BaseController {

    @Autowired
    LeadsService leadsService;

    @Autowired
    RFileLeadsService rFileLeadsService;

    @Autowired
    FileService fileService;

    @Autowired
    ConfigService configService;

    @Autowired
    LeadsDataService leadsDataService;

    @Autowired
    LogService logService;

    @ApiOperation("添加线索")
    @RequiresAuthentication//登陆状态
    @RequestMapping(value = "/insertSelective", method = RequestMethod.POST)
    public Result insertSelective(@RequestBody Param param) {
        List<Integer> listId = new ArrayList<Integer>();
        Leads leads = param.getLeads();
        LeadsData leadsData = param.getLeadsData();
        if (leads != null) {
            leads.setCreator_role_id(getUser().getUser_id());
            leads.setCreate_time(DateUtil.timeMillis());
            leads.setUpdate_time(DateUtil.timeMillis());
            leads.setIs_deleted(0);
            leads.setDelete_role_id(0);
            leads.setDelete_time(0);
            leads.setIs_transformed(0);
            leads.setTransform_role_id(0);
            leads.setContacts_id(0);
            leads.setCustomer_id(0);
            leads.setBusiness_id(0);
            String address = leads.getAddress() + "-" + leads.getStreet();
            leads.setAddress(address);
            leads.setHave_time(DateUtil.timeMillis());
            leads.setCompany_id(getUser().getCompany_id());
            int insertLeads = leadsService.insertSelective(leads);
//            LeadsData leadsData  = new LeadsData();
            leadsData.setLeads_id(leads.getLeads_id());
            leadsData.setCompany_id(getUser().getCompany_id());
            int insertLeadsDate = leadsDataService.insert(leadsData);
            List<RFileLeads> list = new ArrayList<>();
            int insertFocus = 0;
            if (leads.getFiles() != null) {
                String[] str = leads.getFiles().split(",");
                for (int i = 0; i < str.length; i++) {
                    listId.add(Integer.parseInt(str[i]));
                }
                for (int i = 0; i < str.length; i++) {
                    RFileLeads rFileLeads = new RFileLeads();
                    rFileLeads.setFile_id(Integer.parseInt(str[i]));
                    rFileLeads.setLeads_id(leads.getLeads_id());
                    rFileLeads.setCompany_id(getUser().getCompany_id());
                    list.add(rFileLeads);
                }
                insertFocus = rFileLeadsService.insertFile(list);
            }
            if (insertLeads > 0 && insertLeadsDate > 0 || insertFocus > 0) {
                return Result.success(leads.getLeads_id(), "添加成功！");
            } else {
                fileService.deleteFile(listId);
                return Result.error(CodeMsg.ERROR, "添加失败！");
            }
        } else {
            return Result.error(CodeMsg.ERROR, "请输入要添加的线索信息！");
        }
    }

    @ApiOperation("修改线索")
    @RequiresAuthentication//登陆状态
    @RequestMapping(value = "/updateByPrimaryKeySelective", method = RequestMethod.POST)
    public Result updateByPrimaryKeySelective(@RequestBody Param param) {
        Leads leads = param.getLeads();
        LeadsData leadsData = param.getLeadsData();
        if (leads != null && leadsData != null) {
            String address = leads.getAddress() + "-" + leads.getStreet();
            leads.setAddress(address);
            leads.setUpdate_time(DateUtil.timeMillis());
            int insertLeads = leadsService.updateByPrimaryKeySelective(leads);
            int insertLeadsData = leadsDataService.updateByPrimaryKeySelective(leadsData);
            if (insertLeads > 0 && insertLeadsData > 0) {
                return Result.success(insertLeads, "修改成功！");
            } else {
                return Result.error(CodeMsg.ERROR, "修改失败！");
            }
        } else {
            return Result.error(CodeMsg.ERROR, "请输入要修改的线索信息！");
        }
    }

    @ApiOperation("根据id查看线索信息")
    @RequiresAuthentication//登陆状态
    @RequestMapping(value = "/selectByPrimaryKey", method = RequestMethod.POST)
    public Result selectByPrimaryKey(Integer leads_id, Integer company_id) {
        Map list = new HashMap();
        List<String> nullList = new ArrayList<>();
        if (leads_id != null && company_id != null) {
            List<Map<String, String>> selectLead = leadsService.selectByPrimaryKey(leads_id, company_id);
            List<Map<String, String>> fileLeads = fileService.selectByleadsId(leads_id, company_id);
            List<Map<String, List<String>>> newList = new ArrayList<Map<String, List<String>>>();


            List<Map<String, List<String>>> oldList = new ArrayList<Map<String, List<String>>>();
            Map<String, List<String>> newMap = new HashMap<String, List<String>>();//准备存放新的数据类型
            for (int i = 0; i < fileLeads.size(); i++) {
                if (fileLeads.get(i).get("type").equals("img")) {
                    fileLeads.get(i).put("file_path", fileLeads.get(i).get("file_path") + ",");
                }
                if (fileLeads.get(i).get("type").equals("video")) {
                    fileLeads.get(i).put("file_path", fileLeads.get(i).get("file_path") + ",");
                }
                if (fileLeads.get(i).get("type").equals("file")) {
                    fileLeads.get(i).put("file_path", fileLeads.get(i).get("file_path") + ",");
                }
                String type = "";
                Map<String, String> newTemMap = fileLeads.get(i);
                List<String> pathList = new ArrayList<String>();
                for (Map.Entry<String, String> m : newTemMap.entrySet()) {
                    if (m.getValue().indexOf(",") != -1) {
                        String[] path = m.getValue().split(",");
                        for (int j = 0; j < path.length; j++) {
                            pathList.add(path[j]);
                        }
                    } else {
                        type = m.getValue();
                    }
                    if (type != "" && type != null) {
                        newMap.put(type, pathList);
                    }
                }
                newList.add(newMap);
            }
            if (newList.size() < 3) {
                if (newList.size() <= 0) {
                    newMap.put("file", new ArrayList<>());
                    newMap.put("img", new ArrayList<>());
                    newMap.put("video", new ArrayList<>());
                    newList.add(newMap);
                } else {
                    for (int i = 0; i < 2; i++) {
                        if (!newList.get(i).containsKey("file")) {
                            newMap.put("file", new ArrayList<>());
                            newList.add(newMap);
                        }
                        if (!newList.get(i).containsKey("img")) {
                            newMap.put("img", new ArrayList<>());
                            newList.add(newMap);
                        }
                        if (!newList.get(i).containsKey("video")) {
                            newMap.put("video", new ArrayList<>());
                            newList.add(newMap);
                        }
                    }
                }
            }
            oldList.add(newList.get(0));
            List<Map<String, String>> selectLog = logService.selectLog(leads_id, company_id);
            if (selectLead.size() > 0) {
                Map<String, String> newsMap = new HashMap<>();
                newsMap.put("leads_id", selectLead.get(0).get("leads_id"));
                newsMap.put("owner_role_id", selectLead.get(0).get("owner_role_id"));
                newsMap.put("creator_role_id", selectLead.get(0).get("creator_role_id"));
                newsMap.put("name", selectLead.get(0).get("name"));
                newsMap.put("position", selectLead.get(0).get("position"));
                newsMap.put("contacts_name", selectLead.get(0).get("contacts_name"));
                newsMap.put("saltname", selectLead.get(0).get("saltname"));
                newsMap.put("mobile", selectLead.get(0).get("mobile"));
                newsMap.put("email", selectLead.get(0).get("email"));
                newsMap.put("create_time", selectLead.get(0).get("create_time"));
                newsMap.put("update_time", selectLead.get(0).get("update_time"));
                newsMap.put("is_transformed", selectLead.get(0).get("is_transformed"));
                newsMap.put("nextstep", selectLead.get(0).get("nextstep"));
                newsMap.put("nextstep_time", selectLead.get(0).get("nextstep_time"));
                newsMap.put("have_time", selectLead.get(0).get("have_time"));
                newsMap.put("address", selectLead.get(0).get("address"));
                newsMap.put("source", selectLead.get(0).get("source"));
                newsMap.put("crm_oswudq", selectLead.get(0).get("crm_oswudq"));
                newsMap.put("company_id", selectLead.get(0).get("company_id"));
                newsMap.put("crm_iiahks", selectLead.get(0).get("crm_iiahks"));
                newsMap.put("crm_zhheda", selectLead.get(0).get("crm_zhheda"));
                newsMap.put("description", selectLead.get(0).get("description"));
                newsMap.put("ownerName", selectLead.get(0).get("ownerName"));
                if (selectLead.size() > 1) {
                    newsMap.put("creatorName", selectLead.get(1).get("creatorName"));
                } else {
                    newsMap.put("creatorName", selectLead.get(0).get("creatorName"));
                }

                list.put("selectLead", newsMap);
                list.put("fileLeads", oldList);
                if(selectLog.size()>0){
                    for (int k = 0; k < selectLog.size(); k++) {
                        Map mapLog = new HashMap();
                        mapLog.put("log_id",selectLog.get(k).get("log_id"));
                        mapLog.put("create_date",selectLog.get(k).get("create_date"));
                        mapLog.put("subject",selectLog.get(k).get("subject"));
                        mapLog.put("content",selectLog.get(k).get("content "));
                        mapLog.put("name",selectLog.get(k).get("name"));
                        list.put("leadsLog",selectLog);
                    }
                }else{
                    list.put("leadsLog", nullList);
                }
                return Result.success(list);
            } else {
                list.put("selectLead", "");
                list.put("fileLeads", nullList);
                list.put("leadsLog", nullList);
                return Result.success(list, "暂无数据");
            }
        } else {
            return Result.error(CodeMsg.ERROR, "请输入要查询的线索的id和公司id！");
        }
    }

    @ApiOperation("根据id删除线索(可批量删除）")
    @RequiresAuthentication//登陆状态
    @RequestMapping(value = "/deleteLeads", method = RequestMethod.POST)
    public Result deleteLeads(String leads_id, Integer company_id) {
        if (leads_id != null) {
            List<Integer> list = new ArrayList<Integer>();
            String[] str = leads_id.split(",");
            for (int i = 0; i < str.length; i++) {
                list.add(Integer.parseInt(str[i]));
            }
            Integer creator_role_id = getUser().getRole_id();//获取当前登陆人id
            Integer thisData = DateUtil.timeMillis();//取得当前时间戳（精确到秒10位）
            int deleteLeads = leadsService.deleteLeads(creator_role_id, company_id, thisData, list);
            if (deleteLeads > 0) {
                return Result.success(deleteLeads, "删除成功！");
            } else {
                return Result.error(CodeMsg.ERROR, "删除失败！");
            }
        } else {
            return Result.error(CodeMsg.ERROR, "请选择要删除的线索");
        }
    }

    @ApiOperation("我的线索")
    @RequiresAuthentication//登陆状态
    @RequestMapping(value = "/selectAllLeads", method = RequestMethod.GET)
    public Result selectAllLeads(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Map<String, Object> mapDay = new HashMap();
        Integer userId = JwtUtil.getUserId();
        System.out.println(getUser().getCompany_id());
        Integer qw = configService.getByDay();
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", userId);
        map.put("company_id", getUser().getCompany_id());
        map.put("dueDay", qw);
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        PageInfo<Map<String, Object>> pageInfo = leadsService.selectAllLeads(map);
        mapDay.put("data", pageInfo.getList());
        mapDay.put("total", pageInfo.getTotal());
        if (pageInfo.getSize() > 0) {
            return Result.success(mapDay, "查询成功！");
        } else {
            List<String> list = new ArrayList<>();
            mapDay.put("data", list);
            mapDay.put("total", "");
            return Result.success(mapDay, "暂无数据！");
        }
    }

    @ApiOperation("线索池（可查看本公司下所有的线索）")
    @RequiresAuthentication//登陆状态
    @RequestMapping(value = "/selectAllPool", method = RequestMethod.GET)
    public Result selectAllPool(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Map<String, Object> mapDay = new HashMap();
        Integer qw = configService.getByDay();
        Map<String, Object> map = new HashMap<>();
        map.put("company_id", getUser().getCompany_id());
        map.put("have_time", DateUtil.timeMillis());
        map.put("dueDay", qw);
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        PageInfo<Map<String, Object>> pageInfo = leadsService.selectAllPool(map);
        mapDay.put("data", pageInfo.getList());
        mapDay.put("total", pageInfo.getTotal());
        if (pageInfo.getSize() > 0) {
            return Result.success(mapDay, "查询成功！");
        } else {
            List<String> listPool = new ArrayList<>();
            mapDay.put("data", listPool);
            mapDay.put("total", "");
            return Result.success(mapDay, "暂无线索池数据！");
        }
    }

    @ApiOperation("领取线索")
    @RequiresAuthentication//登陆状态
    @RequestMapping(value = "/getToReceive", method = RequestMethod.POST)
    public Result getToReceive(String leads_id) {
        if (leads_id != null) {
            List<Integer> list = new ArrayList<Integer>();
            String[] str = leads_id.split(",");
            Integer newTime = 0;
            for (int i = 0; i < str.length; i++) {
                list.add(Integer.parseInt(str[i]));
                newTime = DateUtil.timeMillis();
            }
            int getLeads = leadsService.getToReceive(list, newTime, getUser().getUser_id());
            if (getLeads > 0) {
                return Result.success(getLeads, "领取成功！");
            } else {
                return Result.error(CodeMsg.ERROR, "领取失败！");
            }
        } else {
            return Result.error(CodeMsg.ERROR, "请选择要领取的线索！");
        }
    }

    @ApiOperation("放入线索池")
    @RequiresAuthentication//登陆状态
    @RequestMapping(value = "/putCuePool", method = RequestMethod.POST)
    public Result putCuePool(String leads_id) {
        if (leads_id != null) {
            List<Integer> list = new ArrayList<Integer>();
            String[] str = leads_id.split(",");
            for (int i = 0; i < str.length; i++) {
                list.add(Integer.parseInt(str[i]));
            }
            int getLeads = leadsService.putCuePool(list);
            if (getLeads > 0) {
                return Result.success(getLeads, "放入线索池成功！");
            } else {
                return Result.error(CodeMsg.ERROR, "放入线索池失败！");
            }
        } else {
            return Result.error(CodeMsg.ERROR, "请选择要放入线索池的线索！");
        }
    }

    @ApiOperation("删除线索附件")
    @RequiresAuthentication//登陆状态
    @RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
    public Result deleteLeadsFile(@RequestBody Map<String, String> file_path) {
        if (file_path.size() > 0) {
            boolean deleteFile = fileService.deleteLeadsFile(file_path.get("file_path"));
            String str1 = file_path.get("file_path").substring(47, file_path.get("file_path").indexOf("?"));//截取?之前的字符串
            List<String> list = AliyunOSSUtil.deleteFile(str1);
            if (deleteFile == true && list.size() == 0) {
                return Result.success("删除线索附件成功！");
            } else {
                return Result.error(CodeMsg.ERROR, "删除线索附件失败！");
            }
        } else {
            return Result.error(CodeMsg.ERROR, "请选择要删除的线索附件！");
        }
    }

    @ApiOperation("删除线索附件")
    @RequestMapping(value = "/testDelete", method = RequestMethod.POST)
    public Result testDelete(@RequestParam String file_path) {
        String keyPrefix = "1546479568832.jpg";
        AliyunOSSUtil.deleteFile(keyPrefix);
        return Result.success(file_path, "成功！");
    }

}

class Param {
    private Leads leads;
    private LeadsData leadsData;

    public Leads getLeads() {
        return leads;
    }

    public void setLeads(Leads leads) {
        this.leads = leads;
    }

    public LeadsData getLeadsData() {
        return leadsData;
    }

    public void setLeadsData(LeadsData leadsData) {
        this.leadsData = leadsData;
    }
}